﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Globalization;

namespace KgUtils.Wpf.ValidationRules
{
    public class NumericRule : ValidationRule
    {
        /// <summary>
        /// Checks whether a value can be converted to a numeric value.
        /// </summary>
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            Guard.AssertNotNull(cultureInfo, "cultureInfo");

            string input = value as string;

            if (!String.IsNullOrWhiteSpace(input))
            {
                input = input.Replace('.', ',');

                //try conversion
                decimal result;
                if (decimal.TryParse(input, NumberStyles.Number, cultureInfo.NumberFormat, out result))
                    return ValidationResult.ValidResult;
                else
                    return new ValidationResult(false, String.Format("'{0}' n'est pas un nombre valide", input));
            }
            else
                return ValidationResult.ValidResult;
        }
    }
}
